<template>
  <div class="divBox relative">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="车牌号" prop="licensePlateNumber">
            <el-input
              v-model="queryParams.licensePlateNumber"
              placeholder="请输入车牌号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="车辆类型" prop="vehicleType">
            <el-select v-model="queryParams.vehicleType" placeholder="请选择" clearable class="selWidth">
              <el-option label="轿车" :value="1" />
              <el-option label="货车" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="配送员" prop="deliveryPersonnelId">
            <el-input
              v-model="queryParams.deliveryPersonnelId"
              placeholder="请输入配送员"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card mt14" :body-style="{ padding: '0 20px 20px' }" shadow="never" :bordered="false">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="handleAdd"
        v-hasPermi="['platform:vehicle:save']"
        class="mt5"
        >新增车辆</el-button
      >

      <el-table
        v-loading="loading"
        :data="vehicleList"
        style="width: 100%"
        size="small"
        highlight-current-row
        class="mt20"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="车牌号" align="center" prop="licensePlateNumber" />
        <el-table-column label="车辆品牌" align="center" prop="vehicleBrand" />
        <el-table-column label="车辆类型" align="center" prop="vehicleType">
          <template slot-scope="scope">
            {{ scope.row.vehicleType === 1 ? '轿车' : '货车' }}
          </template>
        </el-table-column>
        <el-table-column label="配送员" align="center" prop="deliveryPersonnelName" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            {{ scope.row.sex == '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column label="归属门店" align="center" prop="roomName" />
        <el-table-column label="联系电话" align="center" prop="deliveryPersonnelPhone" />
        <el-table-column label="状态" align="center" prop="vehicleStatus">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.vehicleStatus"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
         
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:vehicle:update']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['platform:vehicle:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加或修改车辆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlateNumber">
              <el-input v-model="form.licensePlateNumber" placeholder="请输入车牌号" class="input-width" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆品牌" prop="vehicleBrand">
              <el-input v-model="form.vehicleBrand" placeholder="请输入车辆品牌" class="input-width" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送员" prop="deliveryPersonnelId">
              <el-select v-model="form.deliveryPersonnelId" placeholder="请选择" clearable class="input-width">
                <el-option v-for="item in deliveryList" :key="item.id" :label="item.deliveryPersonnelName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-select v-model="form.vehicleType" placeholder="请选择" clearable class="input-width">
                <el-option label="轿车" :value="1" />
                <el-option label="货车" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="GPS编号" prop="gpsNumber">
              <el-input v-model="form.gpsNumber" placeholder="请输入GPS编号" class="input-width" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆用途" prop="vehicleUsage">
              <el-select v-model="form.vehicleUsage" placeholder="请选择" clearable class="input-width">
                <el-option label="配送车辆" :value="1" />
                <el-option label="运营车辆" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆状态" prop="vehicleStatus">
              <el-switch
                v-model="form.vehicleStatus"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
                class="input-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注说明"
                class="input-width"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDelivery } from '@/api/delivery';
import { listCar, saveCar, updateCar, deleteCar, getCarInfo } from '@/api/vehicle';
export default {
  name: 'CarManage',
  data() {
    // 车牌号验证规则
   const validateLicensePlate = (rule, value, callback) => {
    // 普通车牌正则：1位省份汉字 + 1位字母 + 5位字母/数字（不含I/O），最后一位可能为特殊汉字[4,5](@ref)
    const normalReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼港澳使领警学][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]$/;
    
    // 新能源车牌正则（小型车：1位省份汉字 + 1位字母 + D/F + 4位数字或字母；大型车：1位汉字 + 1位字母 + 5位数字 + D/F）[2,7,8](@ref)
    const newEnergyReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼港澳使领警学][A-HJ-NP-Z]([DF][A-HJ-NP-Z0-9][0-9]{4}|[0-9]{5}[DF])$/;
    
    if (!value) {
        callback(new Error('请输入车牌号'));
    } else if (value.length < 7 || value.length > 8) {
        callback(new Error('车牌号长度应为7位（普通车牌）或8位（新能源车牌）'));
    } else if (!newEnergyReg.test(value) && !normalReg.test(value)) {
        callback(new Error('格式错误：需符合普通车牌或新能源车牌规则'));
    } else {
        callback();
    }
};

    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆列表
      vehicleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        licensePlateNumber: null,
        vehicleType: null,
        deliveryPersonnelId: null,
      },
      // 表单参数
      form: {
        id: null,
        licensePlateNumber: null,
        vehicleBrand: null,
        vehicleType: null,
        gpsNumber: null,
        vehicleUsage: null,
        vehicleStatus: 1,
        remark: null,
      },
      // 表单校验
      rules: {
        licensePlateNumber: [
          { required: true, message: '车牌号不能为空', trigger: 'blur' },
          { validator: validateLicensePlate, trigger: 'blur' }
        ],
        vehicleBrand: [{ required: true, message: '车辆品牌不能为空', trigger: 'change' }],
        vehicleType: [{ required: true, message: '车辆类型不能为空', trigger: 'change' }],
        vehicleUsage: [{ required: true, message: '车辆用途不能为空', trigger: 'change' }],
      },
      deliveryList: [],
    };
  },
  created() {
    this.getList();
    this.getDeliveryList();
  },
  methods: {
    // 获取配送员列表
    getDeliveryList() {
      listDelivery({ pageNum: 1, pageSize: 9999 }).then((response) => {
        console.log(response);
        this.deliveryList = response.list;
      });
    },
    // 获取列表数据
    getList() {
      listCar(this.queryParams).then((response) => {    
        this.vehicleList = response.list;
        this.total = response.total;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        licensePlateNumber: null,
        vehicleBrand: null,
        vehicleType: null,
        gpsNumber: null,
        vehicleUsage: null,
        vehicleStatus: 1,
        remark: null,
        deliveryPersonnelId: null,
      };
      this.resetForm('form');
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加车辆';
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      // TODO: 调用获取详情API
    //   this.form = JSON.parse(JSON.stringify(row));
    //   this.open = true;
        getCarInfo(row.id).then((response) => {
            this.form = response;
            this.open = true;
            this.title = '修改车辆';
        });
    },
    // 提交按钮
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            // TODO: 调用修改API
            this.updateList(this.form);
          } else {
            // TODO: 调用新增API
            this.addList(this.form);
          }
        }
      });
    },
    addList(params){
      saveCar(params).then((response) => {
        this.$message.success('新增成功');
        this.getList();
        this.open = false;
      });
    },
    updateList(params){
      updateCar(params).then((response) => {
        this.$message.success('修改成功');
        this.getList();
        this.open = false;
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除车牌号为"' + row.licensePlateNumber + '"的车辆？')
        .then(() => {
          // TODO: 调用删除API
        })
        .catch(() => {});
    },
    // 状态修改
    handleStatusChange(row) {
      this.updateList(row);
      this.getList();
    },
    // 每页数量改变
    handleSizeChange(val) {
      this.queryParams.limit = val;
      this.getList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>

<style scoped>
.mt5 {
  margin-top: 5px;
}
.mt14 {
  margin-top: 14px;
}
.mt20 {
  margin-top: 20px;
}
.selWidth {
  width: 240px;
}
.padding-add {
  padding: 20px;
}
.input-width {
  width: 100%;
}
.el-dialog {
  border-radius: 8px;
}
.el-dialog__header {
  border-bottom: 1px solid #dcdfe6;
  padding: 20px;
  margin: 0;
}
.el-dialog__body {
  padding: 30px 20px;
}
.el-dialog__footer {
  border-top: 1px solid #dcdfe6;
  padding: 20px;
}
.dialog-footer {
  text-align: right;
}
.el-form-item {
  margin-bottom: 22px;
}
.el-form-item__error {
  padding-top: 4px;
}
</style>
